<?php
namespace Devcopilot\Controllers;

use Devcopilot\Controllers\Front;
use Devcopilot\Models\Version AS VersionModel;
use Zyucv7\Core\Web\Request;

class Version extends Front
{
    // 获取需求列表（用于关联需求下拉框）
    public function index()
    {
        $this->display('versions');
    }

    // 获取需求列表
    public function list(Request $request)
    {
        // 实际开发中会从数据库获取需求列表
        $page = $request->getInput('page', 1);
        $limit = $request->getInput('limit', 10);
        $model = new VersionModel();
        $query = $model->newQuery();
        $query->select('versions.*, A.app_name as application_name');
        $query->join("INNER JOIN ".$model->getTableName('applications', 'A').' ON A.id = versions.application_id');
        $pager = $query->order('versions.update_time', 'DESC')
            ->paginate(intval($page), intval($limit));
        $this->ok($pager);
    }

    // 添加需求
    public function store(Request $request)
    {
        // 实际开发中会从请求中获取数据并保存到数据库
        $requirement = new VersionModel();
        $form = $request->getInput('form');
        unset($form['id']);
        $requirement->save($form);
        $this->ok();
    }

    // 编辑需求
    public function update(Request $request)
    {
        // 实际开发中会从请求中获取数据并更新数据库中的记录
        $form = $request->getInput('form');
        $requirement = new VersionModel();
        $requirement->save($form);
        $this->ok();
    }

    // 删除需求
    public function destroy(Request $request)
    {
        // 实际开发中会从数据库删除指定ID的需求
        $id = $request->getQuery('id');
        $requirement = new VersionModel();
        $afr = $requirement->delete($id);
        $this->ok($afr);
    }

    // 根据应用ID获取版本列表
    public function getByApplication(Request $request)
    {
        $applicationId = $request->getQuery('appid');
        $model = new VersionModel();
        $list = $model->newQuery()->where('application_id', '=', $applicationId)->order('create_time')->getAll();
        $this->ok($list);
    }
}